import os

from django.apps import AppConfig
from django.conf import settings

from mars.utils.common import get_authcode, read_yaml_config

# 通过配置文件增加host,以便部署
yaml_cfg = read_yaml_config(os.path.join(settings.BASE_DIR, "config/authservice.yml"))

AUTHSERVICE_URL = ""
if isinstance(yaml_cfg["host"], list):
    AUTHSERVICE_URL = yaml_cfg["host"][0]
elif isinstance(yaml_cfg["host"], str):
    AUTHSERVICE_URL = yaml_cfg["host"]


class OauthConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "mars.apps.oauth"

    version_code = 0
    version = ""
    description = ""
    def __init__(self, app_name, app_module) -> None:
        self.version_code = 0
        self.version = "演示版"
        self.description = ""
        super().__init__(app_name, app_module)
    def ready(self):
        domain = ""
        try:
            from mars.apps.systems.models import WechatConfig

            we = WechatConfig.objects.all()
            if we and len(we) > 0:
                domain = we[0].domain.replace("https://", "").replace("http://", "")
                # 去除端口号
                domain = domain.split(":")[0]
        except Exception as e:
            print(e)
            domain = ""
        auth_code = get_authcode(software=1, domain=domain, url=AUTHSERVICE_URL)
        self.version_code = auth_code.get("version_code", 0)
        self.version = auth_code.get("version", "")
        self.description = auth_code.get("description", "")
        return super().ready()
